package com.wmh.baseservice.user.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.read.metadata.ReadSheet;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wmh.baseservice.admin.pojo.AdGoods;
import com.wmh.baseservice.admin.service.AdGoodsService;
import com.wmh.baseservice.common.annotation.parameterverify.ParameterVerify;
import com.wmh.baseservice.common.utils.CommUtil;
import com.wmh.baseservice.common.utils.LogUtil;
import com.wmh.baseservice.common.utils.easyExcel.DataListener;
import com.wmh.baseservice.common.utils.easyExcel.pojo.JinPin;
import com.wmh.baseservice.common.utils.easyExcel.pojo.WriteContrast;
import com.wmh.baseservice.common.utils.page.pojo.PageInfo;
import com.wmh.baseservice.common.utils.page.pojo.PageResult;
import com.wmh.baseservice.common.utils.page.pojo.SortWay;
import com.wmh.baseservice.common.utils.page.util.PageUtil;
import com.wmh.baseservice.common.utils.returnbody.ResultCodeInfo;
import com.wmh.baseservice.common.utils.returnbody.ReturnBody;
import com.wmh.baseservice.common.wechat.ma.template.WxTemplateMsgUtils;
import com.wmh.baseservice.merchant.pojo.*;
import com.wmh.baseservice.merchant.service.*;
import com.wmh.baseservice.skd.pojo.SkdGoodsSpec;
import com.wmh.baseservice.skd.service.SkdGoodsSpecService;
import com.wmh.baseservice.system.pojo.*;
import com.wmh.baseservice.system.service.*;
import com.wmh.baseservice.user.pojo.UsEvaluate;
import com.wmh.baseservice.user.pojo.UsInfo;
import com.wmh.baseservice.user.pojo.vo.TabBarGroupGoods;
import com.wmh.baseservice.user.pojo.vo.VegetableSearch;
import com.wmh.baseservice.user.service.UsEvaluateService;
import com.wmh.baseservice.user.service.UsGroupGoodsOrderService;
import com.wmh.baseservice.user.service.UsInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;
import java.util.stream.Collectors;

@Api(tags = "用户端-公开接口")
@Validated
@RestController
@RequestMapping(value = "user/public")
@Slf4j
public class UsPublicController {
    @Resource
    private MerchantVegetablePlotService merchantVegetablePlotService;
    @Resource
    private MerchantVegetableService merchantVegetableService;
    @Resource
    private UsInfoService usInfoService;
    @Resource
    private UsEvaluateService usEvaluateService;
    @Resource
    private SysCategoryService sysCategoryService;
    @Resource
    private AdGoodsService adGoodsService;
    @Resource
    private MerchantGoodsService merchantGoodsService;
    @Resource
    private MerchantPlotRegionService merchantPlotRegionService;
    @Resource
    private MerchantPlotRentalMenuService merchantPlotRentalMenuService;
    @Resource
    private MerchantGroupGoodsPriceService merchantGroupGoodsPriceService;
    @Resource
    private MerchantGroupGoodsService merchantGroupGoodsService;
    @Resource
    private SkdGoodsSpecService merchantSpecService;
    @Resource
    private MerchantInfoService merchantInfoService;
    @Resource
    private SysBannerService sysBannerService;
    @Resource
    private SysNewsService sysNewsService;
    @Resource
    private SysLocationService sysLocationService;
    @Resource
    private SysParamsService sysParamsService;
    @Resource
    private UsGroupGoodsOrderService usGroupGoodsOrderService;
    @Resource
    private MerchantActivityService merchantActivityService;

    /**
     * ---------------------------------------土地相关----------------------------------------------
     */

    @ApiOperation("土地列表")
    @PostMapping("plot/list")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = String.class, name = "lat", value = "维度", required = false),
            @ApiImplicitParam(paramType = "query", dataTypeClass = String.class, name = "lng", value = "经度", required = false),
            @ApiImplicitParam(paramType = "query", dataTypeClass = Integer.class, name = "type", value = "土地类型 0采摘 1种植 2全部", required = true),
    })
    @ParameterVerify(notNull = "type")
    public String plotList(PageInfo pageInfo, String lat, String lng, Integer type) {
        //封装参数
        Map<String, Object> map = new HashMap<>(16);
        map.put("type", type);
        if (CommUtil.checkNull(lat, lng)) {
            map.put("lat", lat);
            map.put("lng", lng);
        }
        //分页
        PageResult<MerchantVegetablePlot> pageResult = new PageResult<>();
        Page<MerchantVegetablePlot> vegetablePage = new Page<>(pageInfo.getPageNo(), pageInfo.getPageSize());
        IPage<MerchantVegetablePlot> merchantPlotRegionIPage = merchantVegetablePlotService.usPlotList(vegetablePage, map);
        //如果有经纬度按距离排序，如果没有则按创建时间排序
        if (CommUtil.checkNull(lat, lng)) {
            merchantPlotRegionIPage.getRecords().sort(Comparator.comparing(MerchantVegetablePlot::getJuli).reversed());
        } else {
            merchantPlotRegionIPage.getRecords().sort(Comparator.comparing(MerchantVegetablePlot::getCreateTime).reversed());
        }
        pageResult.setPageSize(merchantPlotRegionIPage.getSize()).setPageNo(merchantPlotRegionIPage.getCurrent()).setPages(merchantPlotRegionIPage.getPages()).
                setTotal(merchantPlotRegionIPage.getTotal());
        pageResult.setList(merchantPlotRegionIPage.getRecords());
        return ReturnBody.success(pageResult);
    }

    @ApiOperation("土地详情")
    @PostMapping("plot/detail")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "土地id", required = true),
    })
    @ParameterVerify(notNull = "id")
    public String plotDetail(Long id, String lat, String lng) {
        Map<String, Object> map = new HashMap<>(16);
        map.put("id", id);
        if (CommUtil.checkNull(lat, lng)) {
            map.put("lat", lat);
            map.put("lng", lng);
        }
        MerchantVegetablePlot merchantVegetablePlot = merchantVegetablePlotService.plotDetail(map);
        if (!CommUtil.checkNull(merchantVegetablePlot)) {
            return ReturnBody.error(ResultCodeInfo.PARAM_ERROR);
        }
        merchantVegetablePlot.setRawMerchantId(merchantVegetablePlotService.getMerchantId(merchantVegetablePlot.getId()));
        return ReturnBody.success(merchantVegetablePlot);
    }

    @ApiOperation("产品列表")
    @PostMapping("plot/productList")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "categoryId", value = "分类id", required = false),
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "plotId", value = "土地id", required = true),
    })
//    @ParameterVerify(notNull = "plotId")
    public String productList(PageInfo pageInfo, Long categoryId, Long plotId, Integer type) {
        pageInfo.setTimeScreen("create_time");
        pageInfo.setDefaultSort("create_time", SortWay.DESC);
        //执行分页辅助工具
        Long finalPlotId = plotId;
        PageResult<MerchantVegetable> pageResult = new PageUtil<MerchantVegetable>(pageInfo).startPage((page, queryWrapper) -> {
            queryWrapper.select(MerchantVegetable.TITLE, MerchantVegetable.SALE, MerchantVegetable.GROW_PRICE, MerchantVegetable.PRICE
                    , MerchantVegetable.ID, MerchantVegetable.CATEGORY_ID, MerchantVegetable.AVATAR, MerchantVegetable.MERCHANT_ID
                    , MerchantVegetable.PLOT_ID, MerchantVegetable.INVENTORY);
            queryWrapper.eq(MerchantVegetable.PLOT_ID, finalPlotId).eq(MerchantVegetable.STATUS, 0);
            queryWrapper.in(MerchantVegetable.TYPE, type, 2);
            if (CommUtil.checkNull(categoryId)) {
                queryWrapper.eq(MerchantVegetable.CATEGORY_ID, categoryId);
            }
            merchantVegetableService.page(page, queryWrapper);
        });
        pageResult.setList(pageResult.getList().stream().sorted(Comparator.comparing(MerchantVegetable::getCategoryId)).collect(Collectors.toList()));
        return ReturnBody.success(pageResult);
    }

    @ApiOperation("产品详情")
    @PostMapping("plot/productDetail")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "产品id", required = true),
    })
    public String productDetail(Long id) {
        JSONObject object = new JSONObject(true);
        //详情
        MerchantVegetable merchantVegetable = merchantVegetableService.getById(id);
        if (!CommUtil.checkNull(merchantVegetable)) {
            return ReturnBody.error("该商品已下架或不存在");
        }
        //当前果蔬所属区域信息
        MerchantPlotRegion merchantPlotRegion = merchantPlotRegionService.getById(merchantVegetable.getRegionId());
        MerchantInfo info = merchantInfoService.getById(merchantPlotRegion.getMerchantId());
        object.put("regionName", merchantPlotRegion.getPlotName());
        object.put("merchantPhone", info.getPhone());
        object.put("plotAvatar", info.getStoreAvatar());
        object.put("plotName", info.getStoreName());
        object.put("detail", merchantVegetable);
        //评价列表，2条
        List<UsEvaluate> usEvaluates = usEvaluateService.list(new QueryWrapper<UsEvaluate>().eq(UsEvaluate.ITEM_ID, id).eq(UsEvaluate.TYPE, 1));
        //求和
        double rate = usEvaluates.stream().mapToDouble(UsEvaluate::getRate).sum();
        //保留两位小数，四舍五入
        object.put("rate", (double) Math.round(rate / usEvaluates.size() * 100) / 100);
        Collections.shuffle(usEvaluates);
        usEvaluates = usEvaluates.stream().limit(2).collect(Collectors.toList());
        JSONArray array = new JSONArray();
        if (usEvaluates.size() != 0) {
            usEvaluates.forEach(usEvaluate -> {
                JSONObject evaObj = new JSONObject(true);
                UsInfo usInfo = usInfoService.getById(usEvaluate.getUsId());
                evaObj.put("usEvaluate", usEvaluate);
                evaObj.put("nick", usInfo.getNick());
                evaObj.put("avatar", usInfo.getAvatar());
                array.add(evaObj);
            });
            object.put("eva", array);
        }
        //土地信息
        MerchantVegetablePlot merchantVegetablePlot = merchantVegetablePlotService.getById(merchantVegetable.getPlotId());
        object.put("plotAddress", merchantVegetablePlot.getProvince() + merchantVegetablePlot.getCity() + merchantVegetablePlot.getArea() + merchantVegetablePlot.getAddress());
        return ReturnBody.success(object);
    }

    @ApiOperation("果蔬分类")
    @PostMapping("plot/categoryList")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "id", required = false),
    })
    public String plotCategoryList() {
        return ReturnBody.success(sysCategoryService.listForUpdate(new QueryWrapper<SysCategory>().eq(SysCategory.TYPE, 2)));
    }


    /**
     * ---------------------------------------商城相关----------------------------------------------
     */
    @ApiOperation("商城分类")
    @PostMapping("shop/categoryList")
    public String shopCategoryList() {
        List<SysCategory> sysCategories = sysCategoryService.listForUpdate(new QueryWrapper<SysCategory>().eq(SysCategory.TYPE, 1));
        return ReturnBody.success(sysCategories);
    }

    @ApiOperation("商品列表")
    @PostMapping("shop/list")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "id", required = false),
            @ApiImplicitParam(paramType = "query", dataTypeClass = Integer.class, name = "type", value = "商家商品 平台商品", required = false),
    })
    public String shopList(PageInfo pageInfo, Long categoryId, Integer type, Long id) {
        //封装参数
        if (type == 1) {
            MerchantInfo merchantInfo = merchantInfoService.getByIdForUpdate(id);
            if (merchantInfo.getParentId() != -1) {
                id = merchantInfo.getUsId();
            }
            pageInfo.setTimeScreen("create_time");
            pageInfo.setDefaultSort("create_time", SortWay.DESC);
            Long finalId = id;
            PageResult<MerchantGoods> pageResult = new PageUtil<MerchantGoods>(pageInfo).startPage((page, queryWrapper) -> {
                if (CommUtil.checkNull(categoryId)) {
                    queryWrapper.eq(MerchantGoods.CATEGORY_ID, categoryId);
                }
                queryWrapper.eq(MerchantGoods.MERCHANT_ID, finalId);
                merchantGoodsService.page(page, queryWrapper);
            });
            return ReturnBody.success(pageResult);
        } else {
            pageInfo.setTimeScreen("create_time");
            pageInfo.setDefaultSort("create_time", SortWay.DESC);
            PageResult<AdGoods> pageResult = new PageUtil<AdGoods>(pageInfo).startPage((page, queryWrapper) -> {
                if (CommUtil.checkNull(categoryId)) {
                    queryWrapper.eq(MerchantGoods.CATEGORY_ID, categoryId);
                }
                adGoodsService.page(page, queryWrapper);
            });
            return ReturnBody.success(pageResult);
        }
    }

//    @ApiOperation("商品详情")
//    @PostMapping("shop/detail")
//    @ApiImplicitParams({
//            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "id", required = false),
//            @ApiImplicitParam(paramType = "query", dataTypeClass = Integer.class, name = "type", value = "商家商品 平台商品", required = false),
//    })
//    @ParameterVerify(notNull = {"type", "id"})
//    public String detail(Long id, Integer type) {
//        JSONObject object = new JSONObject(true);
//        if (type == 1) {
//            MerchantGoods merchantGoods = merchantGoodsService.getByIdForUpdate(id);
//            if (!CommUtil.checkNull(merchantGoods) || merchantGoods.getStatus() != 0) {
//                return ReturnBody.error("商品不存在或已下架");
//            }
//            object.put("goods", merchantGoods);
//            List<UsEvaluate> collect = usEvaluateService.listForUpdate(new QueryWrapper<UsEvaluate>().eq(UsEvaluate.TYPE, 2).eq(UsEvaluate.ITEM_ID, merchantGoods.getId())).stream().limit(2).collect(Collectors.toList());
//            object.put("evaList", collect);
//            //规格
//            if (merchantGoods.getHasSpec() == 1) {
//                List<SkdGoodsSpec> merchantSpecs = merchantSpecService.listForUpdate(new QueryWrapper<SkdGoodsSpec>().eq(SkdGoodsSpec.TYPE, 1).eq(SkdGoodsSpec.GOODS_ID, merchantGoods.getId()));
//                object.put("specList", merchantSpecs);
//            }
//        } else {
//            AdGoods adGoods = adGoodsService.getByIdForUpdate(id);
//            if (!CommUtil.checkNull(adGoods) || adGoods.getStatus() != 0) {
//                return ReturnBody.error("商品不存在或已下架");
//            }
//            object.put("goods", adGoods);
//            List<UsEvaluate> collect = usEvaluateService.listForUpdate(new QueryWrapper<UsEvaluate>().eq(UsEvaluate.TYPE, 5).eq(UsEvaluate.ITEM_ID, adGoods.getId())).stream().limit(2).collect(Collectors.toList());
//            object.put("evaList", collect);
//            //规格
//            if (adGoods.getHasSpec() == 1) {
//                List<SkdGoodsSpec> merchantSpecs = merchantSpecService.listForUpdate(new QueryWrapper<SkdGoodsSpec>().eq(SkdGoodsSpec.TYPE, 4).eq(SkdGoodsSpec.GOODS_ID, adGoods.getId()));
//                object.put("specList", merchantSpecs);
//            }
//        }
//        return ReturnBody.success(object);
//    }

    /**
     * ---------------------------------------租赁相关----------------------------------------------
     */

    @ApiOperation("可租赁区域列表")
    @PostMapping("regionList")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = String.class, name = "lat", value = "维度", required = false),
            @ApiImplicitParam(paramType = "query", dataTypeClass = String.class, name = "lng", value = "经度", required = false),
    })
    public String regionList(PageInfo pageInfo, String lat, String lng, String plotName) {
        PageResult<MerchantPlotRegion> pageResult = new PageResult<>();
        Page<MerchantPlotRegion> merchantPlotRegionPage = new Page<>(pageInfo.getPageNo(), pageInfo.getPageSize());
        Map<String, Object> map = new HashMap<>();
        if (CommUtil.checkNull(lat, lng)) {
            map.put("lat", lat);
            map.put("lng", lng);
            map.put("plot_name", plotName);
        }
        IPage<MerchantPlotRegion> merchantPlotRegionIPage = merchantPlotRegionService.usList(merchantPlotRegionPage, map);
        //如果有经纬度按距离排序，如果没有则按创建时间排序
        if (CommUtil.checkNull(lat, lng)) {
            merchantPlotRegionIPage.getRecords().sort(Comparator.comparing(MerchantPlotRegion::getJuli).reversed());
        } else {
            merchantPlotRegionIPage.getRecords().sort(Comparator.comparing(MerchantPlotRegion::getCreateTime).reversed());
        }
        pageResult.setPageSize(merchantPlotRegionIPage.getSize()).setPageNo(merchantPlotRegionIPage.getCurrent()).setPages(merchantPlotRegionIPage.getPages()).
                setTotal(merchantPlotRegionIPage.getTotal());
        pageResult.setList(merchantPlotRegionIPage.getRecords());
        return ReturnBody.success(pageResult);
    }

    @ApiOperation("租赁区域详情")
    @PostMapping("regionDetail")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "区域id", required = true),
    })
    public String regionDetail(Long id) {
        JSONObject object = new JSONObject(true);
        MerchantPlotRegion merchantPlotRegion = merchantPlotRegionService.getByIdForUpdate(id);
        if (!CommUtil.checkNull(merchantPlotRegion) || merchantPlotRegion.getStatus() != 1) {
            return ReturnBody.error(ResultCodeInfo.PARAM_ERROR);
        }
        object.put("region", merchantPlotRegion);
        MerchantVegetablePlot merchantVegetablePlot = merchantVegetablePlotService.getByIdForUpdate(merchantPlotRegion.getPlotId());
        object.put("plot", merchantVegetablePlot);
        List<MerchantPlotRentalMenu> merchantPlotRentalMenus = merchantPlotRentalMenuService.listForUpdate(new QueryWrapper<MerchantPlotRentalMenu>().eq(MerchantPlotRentalMenu.REGION_ID, id));
        object.put("rentMeal", merchantPlotRentalMenus);
        return ReturnBody.success(object);
    }

    /**
     * ---------------------------------------团购商品相关----------------------------------------------
     */

//    @ApiOperation("团购商品列表")
//    @PostMapping("groupGoodsList")
//    @ApiImplicitParams({
//            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "lat", value = "经度", required = true),
//            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "lng", value = "维度", required = true),
//    })
//    @ParameterVerify(notNull = {"lat", "lng"})
//    public String groupGoodsList(PageInfo pageInfo, String search, String lat, String lng) {
//        PageResult<TabBarGroupGoods> pageResult = new PageResult<>();
//        List<TabBarGroupGoods> tabBarGroupGoodsList = new ArrayList<>();
//        Page<MerchantGroupGoods> merchantGroupGoodsPage = new Page<>(pageInfo.getPageNo(), pageInfo.getPageSize());
//        Map<String, Object> map = new HashMap<>();
//        if (CommUtil.checkNull(search)) {
//            map.put("search", search);
//        }
//        SysLocation sysLocation = sysLocationService.getLocationInfo(lng, lat);
//        map.put("locationId", sysLocation.getId());
//        //sql未完善，区域id已获取
//        IPage<MerchantGroupGoods> merchantGroupGoodsIPage = merchantGroupGoodsPriceService.usList(merchantGroupGoodsPage, map);
//
//        merchantGroupGoodsIPage.getRecords().forEach(item -> {
//            List<String> usAvatar = new ArrayList<>();
//            final BigDecimal[] difference = {BigDecimal.ZERO};
//            int[] buyCount = new int[]{0};
//            int[] successGear = new int[]{0};
//            int[] differ = new int[]{0};
//            final BigDecimal[] cashBack = {BigDecimal.ZERO};
//            final BigDecimal[] minPrice = {BigDecimal.ZERO};
//            final BigDecimal[] originPrice = {BigDecimal.ZERO};
//            final BigDecimal[] currentPrice = {BigDecimal.ZERO};
//
//            buyCount[0] = 99999;
//            minPrice[0] = new BigDecimal("999999");
//            TabBarGroupGoods tabBarGroupGoods = new TabBarGroupGoods();
//            tabBarGroupGoods.setId(item.getId());
//            tabBarGroupGoods.setAvatar(item.getAvatar());
//            tabBarGroupGoods.setTitle(item.getTitle());
//            tabBarGroupGoods.setSales(item.getSale());
//
//            map.clear();
//            map.put("batch", item.getBatchNum());
//            map.put("groupGoodsId", item.getId());
//            int count = usGroupGoodsOrderService.totalCount(map);
//
//            //查询所有优惠档位
//            List<MerchantGroupGoodsPrice> merchantGroupGoodsPrice = merchantGroupGoodsPriceService.listForUpdate(new QueryWrapper<MerchantGroupGoodsPrice>().eq(MerchantGroupGoodsPrice.GROUP_GOODS_ID, item.getId()));
//            merchantGroupGoodsPrice = merchantGroupGoodsPrice.stream().sorted(Comparator.comparing(MerchantGroupGoodsPrice::getSuccessGear)).collect(Collectors.toList());
//            for (int i = 0; i < merchantGroupGoodsPrice.size(); i++) {
//                MerchantGroupGoodsPrice price = merchantGroupGoodsPrice.get(i);
//                if (count >= price.getSuccessGear()) {
//                    currentPrice[0] = price.getDiscountPrice();
//                }
//            }
//            merchantGroupGoodsPrice = merchantGroupGoodsPrice.stream().sorted(Comparator.comparing(MerchantGroupGoodsPrice::getDiscountPrice)).collect(Collectors.toList());
//            merchantGroupGoodsPrice.forEach(price -> {//5,15,20  ----  16单
//                map.clear();
//                map.put("batch", item.getBatchNum());
//                //判断当前档案是否有规格
//                if (CommUtil.checkNull(price.getSpecId())) {
//                    //查出当前档位购买数量
//                    map.put("specId", price.getSpecId());
//                    int totalCount = usGroupGoodsOrderService.totalCount(map);
//                    //查出规格原价
//                    SkdGoodsSpec skdGoodsSpec = merchantSpecService.getByIdForUpdate(price.getSpecId());
//                    originPrice[0] = skdGoodsSpec.getOriginPrice();
//                    //差价=原价-优惠价
//                    BigDecimal currentDifference = skdGoodsSpec.getOriginPrice().subtract(price.getDiscountPrice());
//                    //差值=当前优惠档位拼团成功人数-当前购买数量
//                    int buy = price.getSuccessGear() - totalCount;
//                    if (buy > 0) {
//                        //如果比上一个档位的差值小，则替换
//                        if (buy < buyCount[0]) {
//                            minPrice[0] = price.getDiscountPrice();
//                            successGear[0] = price.getSuccessGear();
//                            originPrice[0] = skdGoodsSpec.getOriginPrice();
//                            cashBack[0] = price.getDiscountPrice();
//                            buyCount[0] = buy;
//                            differ[0] = totalCount;
//                            difference[0] = currentDifference;
//                        }
//                        //如果差值(即将成功档位人数)跟上一个档位相同，并且当前差价比上一个差价大，那么也替换
//                        if (buy == buyCount[0]) {
//                            if (currentDifference.compareTo(difference[0]) > 0) {
//                                minPrice[0] = price.getDiscountPrice();
//                                successGear[0] = price.getSuccessGear();
//                                originPrice[0] = skdGoodsSpec.getOriginPrice();
//                                cashBack[0] = price.getDiscountPrice();
//                                buyCount[0] = buy;
//                                differ[0] = totalCount;
//                                difference[0] = currentDifference;
//                            }
//                        }
//                    }
//                } else {
//                    //查出当前档位购买数量
//                    map.put("groupGoodsId", price.getGroupGoodsId());
//                    int totalCount = usGroupGoodsOrderService.totalCount(map);
//                    //原价
//                    originPrice[0] = item.getOriginalPrice();
//                    //差价=原价-优惠价
//                    BigDecimal currentDifference = item.getOriginalPrice().subtract(price.getDiscountPrice());
//                    //差值=当前优惠档位拼团成功人数-当前购买数量
//                    int buy = price.getSuccessGear() - totalCount;
//                    if (buy > 0) {
//                        //如果比上一个档位的差值小，则替换
//                        if (buy < buyCount[0]) {
//                            minPrice[0] = price.getDiscountPrice();
//                            successGear[0] = price.getSuccessGear();
//                            originPrice[0] = item.getOriginalPrice();
//                            cashBack[0] = price.getDiscountPrice();
//                            buyCount[0] = buy;
//                            differ[0] = totalCount;
//                            difference[0] = currentDifference;
//                        }
//                        //如果差值(即将成功档位人数)跟上一个档位相同，并且当前差价比上一个差价大，那么也替换
//                        if (buy == buyCount[0]) {
//                            if (currentDifference.compareTo(difference[0]) > 0) {
//                                minPrice[0] = price.getDiscountPrice();
//                                successGear[0] = price.getSuccessGear();
//                                originPrice[0] = item.getOriginalPrice();
//                                cashBack[0] = price.getDiscountPrice();
//                                buyCount[0] = buy;
//                                differ[0] = totalCount;
//                                difference[0] = currentDifference;
//                            }
//                        }
//                    }
//                }
//            });
//            //获取最大返现值
//            BigDecimal maxNum;
//            BigDecimal goodsMinPrice = merchantGroupGoodsPrice.stream().min(Comparator.comparing(MerchantGroupGoodsPrice::getDiscountPrice)).get().getDiscountPrice();
//            if (item.getHasSpec() == 1) {
//                List<SkdGoodsSpec> merchantSpecs = merchantSpecService.listForUpdate(new QueryWrapper<SkdGoodsSpec>().eq(SkdGoodsSpec.TYPE, 2).eq(SkdGoodsSpec.GOODS_ID, item.getId()));
//                List<BigDecimal> priceList = new ArrayList<>();
//                assert merchantSpecs != null;
//                merchantSpecs.forEach(spec -> {
//                    List<MerchantGroupGoodsPrice> specPrices = merchantGroupGoodsPriceService.listForUpdate(new QueryWrapper<MerchantGroupGoodsPrice>().eq(MerchantGroupGoodsPrice.GROUP_GOODS_ID, item.getId())
//                            .eq(MerchantGroupGoodsPrice.SPEC_ID, spec.getId()));
//                    //找出当前规格最优惠的价格
//                    BigDecimal min = specPrices.stream().min(Comparator.comparing(MerchantGroupGoodsPrice::getDiscountPrice)).get().getDiscountPrice();
//                    //当前规格差价存到列表中，等规格遍历完后遍历该列表获取最大差价
//                    priceList.add(spec.getOriginPrice().subtract(min));
//                });
//                maxNum = priceList.stream().max(Comparator.comparing(BigDecimal::doubleValue)).get();
//            } else {
//                maxNum = item.getOriginalPrice().subtract(goodsMinPrice);
//            }
//            tabBarGroupGoods.setOriginPrice(originPrice[0]);
//            tabBarGroupGoods.setBuyCount(differ[0]);
//            tabBarGroupGoods.setSuccessGear(successGear[0]);
//            tabBarGroupGoods.setCashBack(cashBack[0]);
//            tabBarGroupGoods.setMinPrice(minPrice[0]);
//            tabBarGroupGoods.setTotalCashBack(maxNum);
//            tabBarGroupGoods.setGoodsMinPrice(goodsMinPrice);
//            tabBarGroupGoods.setCurrentPrice(currentPrice[0].compareTo(BigDecimal.ZERO) <= 0 ? originPrice[0] : currentPrice[0]);
//            //已购买的用户列表头像
//            List<Long> usGroupGoodsOrders = usGroupGoodsOrderService.thyDayUsAvatar(item.getId(), item.getBatchNum());
//            Collections.shuffle(usGroupGoodsOrders);
//            usGroupGoodsOrders = usGroupGoodsOrders.stream().limit(5).collect(Collectors.toList());
//            usGroupGoodsOrders.forEach(usId -> {
//                UsInfo usInfo = usInfoService.getByIdForUpdate(usId);
//                usAvatar.add(usInfo.getAvatar());
//            });
//            tabBarGroupGoods.setUsAvatar(usAvatar);
//            tabBarGroupGoodsList.add(tabBarGroupGoods);
//        });
//        pageResult.setPageSize(merchantGroupGoodsIPage.getSize()).setPageNo(merchantGroupGoodsIPage.getCurrent()).setPages(merchantGroupGoodsIPage.getPages()).
//                setTotal(merchantGroupGoodsIPage.getTotal());
//        pageResult.setList(tabBarGroupGoodsList);
//        return ReturnBody.success(pageResult);
//    }

//    @ApiOperation("团购商品详情")
//    @PostMapping("groupGoods/detail")
//    @ApiImplicitParams({
//            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "团购商品id", required = false),
//    })
//    @ParameterVerify(notNull = "id")
//    public String detail(Long id) {
//        // where 条件映射
//        Map<String, Object> map = new HashMap<>();
//        JSONObject object = new JSONObject(true);
//        //商品信息
//        MerchantGroupGoods merchantGroupGoods = merchantGroupGoodsService.getByIdForUpdate(id);
//        object.put("merchantGroupGoods", merchantGroupGoods);
//        //规格列表
//
//        List<SkdGoodsSpec> merchantSpecs = null;
//        // 指定当前商品批次
//        map.put("batch", merchantGroupGoods.getBatchNum());
//        // 是否有规格
//        if (merchantGroupGoods.getHasSpec() == 1) {
//            // 得到当前团购商品的规格列表
//            merchantSpecs = merchantSpecService.listForUpdate(new QueryWrapper<SkdGoodsSpec>().eq(SkdGoodsSpec.TYPE, 2).eq(SkdGoodsSpec.GOODS_ID, merchantGroupGoods.getId()));
//            merchantSpecs.forEach(item -> {
//                map.put("specId", item.getId());
//                // 得到当前团购当前规格已下单的数量
//                int totalCount = usGroupGoodsOrderService.totalCount(map);
//
//                // 得到当前规格的具体优惠挡位列表 升序排序
//                List<MerchantGroupGoodsPrice> priceList = merchantGroupGoodsPriceService.list(new QueryWrapper<MerchantGroupGoodsPrice>()
//                        .eq(MerchantGroupGoodsPrice.SPEC_ID, item.getId())
//                        .orderByAsc(MerchantGroupGoodsPrice.SUCCESS_GEAR));
//
//                // 如果没查到 将该规格未达成优惠的购买数量设为 0
//                if (priceList.size() == 0) {
//                    totalCount = 0;
//                    LogUtil.warn("获取商品规格失败 : {}", item);
//                }
////                    // 最小优惠挡位达成数量
////                    Integer min = priceList.get(0).getSuccessGear();
////                    // 最大优惠挡位达成数量
////                    Integer max = priceList.get(priceList.size() - 1).getSuccessGear();
////                    // (当前批次购买数量 % 最大挡位达成数量 > 最小挡位挡位达成数量 ?
////                    // 当前批次购买数量 % 最大挡位达成数量 % 最小挡位挡位达成 : 当前批次购买数量 % 最大挡位达成数量)
////                    int t = totalCount % max;
////                    totalCount = t > min ? t % min : t;
////                }
//                item.setRemark(String.valueOf(totalCount));
//            });
//            object.put("specList", merchantSpecs);
//        } else {
//            map.put("groupGoodsId", merchantGroupGoods.getId());
//            int totalCount = usGroupGoodsOrderService.totalCount(map);
//            merchantGroupGoods.setRemark(String.valueOf(totalCount));
//        }
//        //优惠价格档位
//        List<MerchantGroupGoodsPrice> groupGoodsPrices = merchantGroupGoodsPriceService.listForUpdate(new QueryWrapper<MerchantGroupGoodsPrice>().eq(MerchantGroupGoodsPrice.GROUP_GOODS_ID, id));
//        object.put("groupGoodsPrices", groupGoodsPrices);
//        //店铺信息
//        MerchantInfo merchantInfo = merchantInfoService.getOneForUpdate(new QueryWrapper<MerchantInfo>().select(MerchantInfo.STORE_AVATAR, MerchantInfo.STORE_NAME, MerchantInfo.PHONE).eq(MerchantInfo.ID, merchantGroupGoods.getMerchantId()));
//        object.put("shopInfo", merchantInfo);
//        //评价列表，两条
//        List<UsEvaluate> usEvaluates = usEvaluateService.listForUpdate(new QueryWrapper<UsEvaluate>().eq(UsEvaluate.ITEM_ID, id).eq(UsEvaluate.TYPE, 4));
//        //求和
//        double rate = usEvaluates.stream().mapToDouble(UsEvaluate::getRate).sum();
//        //保留两位小数，四舍五入
//        object.put("rate", (double) Math.round(rate / usEvaluates.size() * 100) / 100);
//        Collections.shuffle(usEvaluates);
//        usEvaluates = usEvaluates.stream().limit(2).collect(Collectors.toList());
//        JSONArray array = new JSONArray();
//        if (usEvaluates.size() != 0) {
//            usEvaluates.forEach(usEvaluate -> {
//                JSONObject evaObj = new JSONObject(true);
//                UsInfo usInfo = usInfoService.getByIdForUpdate(usEvaluate.getUsId());
//                evaObj.put("usEvaluate", usEvaluate);
//                evaObj.put("nick", usInfo.getNick());
//                evaObj.put("avatar", usInfo.getAvatar());
//                array.add(evaObj);
//            });
//            object.put("eva", array);
//        }
//        //拼团中的成员
//        List<Long> usGroupGoodsOrders = usGroupGoodsOrderService.thyDayUsAvatar(id, merchantGroupGoods.getBatchNum());
//        JSONArray orderArray = new JSONArray();
//        usGroupGoodsOrders.forEach(item -> {
//            UsInfo usInfo = usInfoService.getByIdForUpdate(item);
//            JSONObject orderObj = new JSONObject(true);
//            orderObj.put("avatar", usInfo.getAvatar());
//            orderObj.put("nick", usInfo.getNick());
//            orderArray.add(orderObj);
//        });
//        object.put("orderList", orderArray);
//        //最大可返现
//        BigDecimal maxNum;
//        map.clear();
//        if (merchantGroupGoods.getHasSpec() == 1) {
//            List<BigDecimal> priceList = new ArrayList<>();
//            assert merchantSpecs != null;
//            merchantSpecs.forEach(spec -> {
//                List<MerchantGroupGoodsPrice> specPrices = merchantGroupGoodsPriceService.listForUpdate(
//                        new QueryWrapper<MerchantGroupGoodsPrice>()
//                                .eq(MerchantGroupGoodsPrice.GROUP_GOODS_ID, id)
//                                .eq(MerchantGroupGoodsPrice.SPEC_ID, spec.getId()));
//                //找出当前规格最优惠的价格
//                BigDecimal min = specPrices.stream().min(Comparator.comparing(MerchantGroupGoodsPrice::getDiscountPrice)).get().getDiscountPrice();
//                //当前规格差价存到列表中，等规格遍历完后遍历该列表获取最大差价
//                priceList.add(spec.getOriginPrice().subtract(min));
//            });
//            maxNum = priceList.stream().max(Comparator.comparing(BigDecimal::doubleValue)).get();
//        } else {
//            map.put("groupGoodsId", merchantGroupGoods.getId());
//            BigDecimal min = groupGoodsPrices.stream().min(Comparator.comparing(MerchantGroupGoodsPrice::getDiscountPrice)).get().getDiscountPrice();
//            maxNum = merchantGroupGoods.getOriginalPrice().subtract(min);
//            //无规格当前达标人数
//            object.put("current", usGroupGoodsOrderService.totalCount(map));
//        }
//        object.put("maxNumber", maxNum);
//        return ReturnBody.success(object);
//    }


    @ApiOperation("判断用户是否在团购商品配送区域内")
    @PostMapping("goodsAreaHasUser")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "团购商品id", required = false),
            @ApiImplicitParam(paramType = "query", dataTypeClass = Integer.class, name = "lat", value = "维度", required = false),
            @ApiImplicitParam(paramType = "query", dataTypeClass = Integer.class, name = "lng", value = "经度", required = false),
    })
    @ParameterVerify(notNull = {"goodsId"})
    public String goodsAreaHasUser(String lng, String lat, String city, Long goodsId) {
        // 得到地区名称
        int result = CommUtil.checkNull(lng, lat) ? 1 :
                (CommUtil.checkNull(city) ? 2 : 0);
        if (result == 0) {
            return ReturnBody.error(ResultCodeInfo.PARAM_ERROR);
        }
        String name = result == 1 ?
                sysLocationService.getLocationInfo(lng, lat).getName()
                : city;
        LogUtil.info("name : {}", name);
        SysLocation location = sysLocationService.getOneForUpdate(
                new QueryWrapper<SysLocation>()
                        .eq(SysLocation.NAME, name).select(SysLocation.ID));
        if (!CommUtil.checkNull(location)) {
            return ReturnBody.error();
        }
        MerchantGroupGoods goods = merchantGroupGoodsService.getOneForUpdate(
                new QueryWrapper<MerchantGroupGoods>()
                        .eq(MerchantGroupGoods.ID, goodsId).select(MerchantGroupGoods.LOCATION_IDS, MerchantGroupGoods.ID));
        LogUtil.info("商品支持的配送区域 : {} 用户所在区域 : {}", goods.getLocationIds(), location.getId());
        boolean match = Arrays.stream(goods.getLocationIds().split(",")).anyMatch(s -> Integer.valueOf(s).equals(location.getId()));
        return ReturnBody.success(match);
    }

    /**
     * ---------------------------------------轮播图相关----------------------------------------------
     */

    @ApiOperation("轮播图列表")
    @PostMapping("bannerList")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = String.class, name = "type", value = "0附近好地 1商城", required = true),
    })
    public String bannerList(PageInfo pageInfo, Integer type) {
        pageInfo.setDefaultSort(SysBanner.SORT, SortWay.ASC);
        //执行分页辅助工具
        PageResult<SysBanner> pageResult = new PageUtil<SysBanner>(pageInfo).startPage((page, queryWrapper) -> {
            if (CommUtil.checkNull(type)) {
                queryWrapper.eq(SysBanner.TYPE, type);
            }
            sysBannerService.page(page, queryWrapper);
        });
        return ReturnBody.success(pageResult);
    }


    /**
     * ---------------------------------------文章资讯----------------------------------------------
     */

    @ApiOperation("文章列表")
    @PostMapping("newsList")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "categoryId", value = "分类id", required = true),
    })
    public String newsList(Long categoryId, PageInfo pageInfo) {
        pageInfo.setTimeScreen("create_time");
        pageInfo.setDefaultSort("create_time", SortWay.DESC);
        //执行分页辅助工具
        PageResult<SysNews> pageResult = new PageUtil<SysNews>(pageInfo).startPage((page, queryWrapper) -> {
            if (CommUtil.checkNull(categoryId)) {
                queryWrapper.eq(SysNews.CATEGORY_ID, categoryId);
            }
            queryWrapper.select(SysNews.TITLE, SysNews.ID, SysNews.AVATAR);
            sysNewsService.page(page, queryWrapper);
        });
        return ReturnBody.success(pageResult);
    }


    @ApiOperation("详情")
    @PostMapping("newsDetails")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "详情id", required = true),
    })
    @ParameterVerify(notNull = "id")
    public String details(Long id) {
        SysNews sysNews = sysNewsService.getByIdForUpdate(id);
        if (!CommUtil.checkNull(sysNews)) {
            return ReturnBody.error(ResultCodeInfo.PARAM_ERROR);
        }
        return ReturnBody.success(sysNews);
    }

    /**
     * ---------------------------------------系统参数相关----------------------------------------------
     */
    @ApiOperation("获取系统参数")
    @PostMapping("getParams")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Integer.class, name = "type", value = "1:首页引导语", required = true),
    })
    @ParameterVerify(notNull = "type")
    public String details(Integer type) {
        SysParams sysParams;
        switch (type) {
            case 1:
                sysParams = sysParamsService.getByIdForUpdate(7L);
                break;
            default:
                return ReturnBody.error(ResultCodeInfo.PARAM_ERROR);
        }
        if (!CommUtil.checkNull(sysParams)) {
            return ReturnBody.error(ResultCodeInfo.PARAM_ERROR);
        }
        return ReturnBody.success(sysParams.getValue());
    }

    @ApiOperation("获取地区")
    @PostMapping("getArea")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Integer.class, name = "lat", value = "维度", required = true),
            @ApiImplicitParam(paramType = "query", dataTypeClass = Integer.class, name = "lng", value = "经度", required = true),
    })
    @ParameterVerify(notNull = {"lat", "lng"})
    public String getArea(String lng, String lat) {
        return ReturnBody.success(sysLocationService.getLocationInfo(lng, lat));
    }


    /**
     * ---------------------------------活动相关--------------------------------------
     */
    @ApiOperation("活动列表")
    @PostMapping("activity/list")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "id", required = false),
    })
    @ParameterVerify(notNull = "plotId")
    public String list(PageInfo pageInfo, Long plotId) {
        pageInfo.setTimeScreen("create_time");
        pageInfo.setDefaultSort("create_time", SortWay.DESC);
        //查出该土地的所有商家id
        List<Long> merchantIds = merchantPlotRegionService.listForUpdate(new QueryWrapper<MerchantPlotRegion>().eq(MerchantPlotRegion.PLOT_ID, plotId))
                .stream().map(MerchantPlotRegion::getMerchantId).collect(Collectors.toList());
        //执行分页辅助工具
        PageResult<MerchantActivity> pageResult = new PageUtil<MerchantActivity>(pageInfo).startPage((page, queryWrapper) -> {
            queryWrapper.select(MerchantActivity.getFields(MerchantActivity.MERCHANT_ID));
            queryWrapper.in(MerchantActivity.MERCHANT_ID, merchantIds);
            merchantActivityService.page(page, queryWrapper);
        });
        return ReturnBody.success(pageResult);
    }

    @ApiOperation("活动详情")
    @PostMapping("activity/detail")
    @ParameterVerify(notNull = "id")
    public String activityDetail(Long id) {
        MerchantActivity result = merchantActivityService.getByIdForUpdate(id);
        if (!CommUtil.checkNull(result)) {
            return ReturnBody.error("获取活动详情失败,请稍后重试");
        }
        return ReturnBody.success(result);
    }

    /**
     * ---------------------------------------搜索相关----------------------------------------------
     */
    @ApiOperation("搜索关键词")
    @PostMapping("search")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Integer.class, name = "type", value = "1:果蔬", required = true),
    })
    @ParameterVerify(notNull = "keyword")
    public String search(PageInfo pageInfo, String keyword, String lat, String lng, Integer type) {
        if (CommUtil.checkNull(type)) {
            Map<String, Object> map = new HashMap<>();
            if (CommUtil.checkNull(lat, lng)) {
                map.put("lat", lat);
                map.put("lng", lng);
            }
            map.put("keyword", keyword);
            switch (type) {
                case 1:
                    PageResult<VegetableSearch> pageResult = new PageResult<>();
                    Page<VegetableSearch> vegetablePage = new Page<>(pageInfo.getPageNo(), pageInfo.getPageSize());
                    IPage<VegetableSearch> searchList = merchantVegetableService.search(vegetablePage, map);
                    pageResult.setPageSize(searchList.getSize()).setPageNo(searchList.getCurrent()).setPages(searchList.getPages()).
                            setTotal(searchList.getTotal());
                    pageResult.setList(searchList.getRecords());
                    return ReturnBody.success(pageResult);
                default:
                    return ReturnBody.error(ResultCodeInfo.PARAM_ERROR);
            }
        }
        return ReturnBody.success();
    }


    /**
     * ---------------------------------------测试----------------------------------------------
     */
    @ApiIgnore
    @ApiOperation("test")
    @PostMapping("test")
    public String test() {
        //读取表格
        String fileName = "D:\\竞品(1).xlsx";
        ExcelReader excelReader = EasyExcel.read(fileName, JinPin.class, new DataListener()).build();
        ReadSheet readSheet = EasyExcel.readSheet(1).build();
        excelReader.read(readSheet);
        excelReader.finish();
        //读取完毕
        List<JinPin> list = DataListener.list;
        //流量对比列表
        List<WriteContrast> writeContrasts = new ArrayList<>();
        //转化率列表
        List<WriteContrast> conversionRates = new ArrayList<>();

        String lastName = "";
        WriteContrast writeContrast = new WriteContrast();
        WriteContrast conversionRate = new WriteContrast();

        for (JinPin jinPin : list) {
            String goodsInfo = jinPin.getGoodsInfo();
            if (!jinPin.getShopSource().equals(lastName)) {
                //用来判断是否跳过
                writeContrast = new WriteContrast();
                conversionRate = new WriteContrast();

                lastName = jinPin.getShopSource();
            }
            //流量渠道命名
            writeContrast.setShopSource(jinPin.getShopSource());
            conversionRate.setShopSource(jinPin.getShopSource());

            if (goodsInfo.contains("本店商品")) {
                writeContrast.setMyShop(jinPin.getAccessCount());
                conversionRate.setMyShop(jinPin.getConversionRate());
                continue;
            }
            if (goodsInfo.contains("竞品1")) {
                writeContrast.setVieOne(jinPin.getAccessCount());
                conversionRate.setVieOne(jinPin.getConversionRate());
                continue;
            }
            if (goodsInfo.contains("竞品2")) {
                writeContrast.setVieTwo(jinPin.getAccessCount());
                conversionRate.setVieTwo(jinPin.getConversionRate());
                writeContrasts.add(writeContrast);
                conversionRates.add(conversionRate);
            }
        }

        //去重
        writeContrasts = writeContrasts.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(
                Comparator.comparing(WriteContrast::getShopSource))), ArrayList::new));
        conversionRates = conversionRates.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(
                Comparator.comparing(WriteContrast::getShopSource))), ArrayList::new));

        //计算占比率
        Long mySum = writeContrasts.stream().filter(item -> !"-".equals(item.getMyShop())).mapToLong(item -> Long.parseLong(item.getMyShop())).sum();
        Long vieOneSum = writeContrasts.stream().filter(item -> !"-".equals(item.getVieOne())).mapToLong(item -> Long.parseLong(item.getVieOne())).sum();
        Long vieTwoSum = writeContrasts.stream().filter(item -> !"-".equals(item.getVieTwo())).mapToLong(item -> Long.parseLong(item.getVieTwo())).sum();

        //汇总
        WriteContrast sum = new WriteContrast();
        sum.setShopSource("汇总");
        sum.setMyShop(mySum.toString());
        sum.setVieOne(vieOneSum.toString());
        sum.setVieTwo(vieTwoSum.toString());
        writeContrasts.add(sum);
        DecimalFormat df = new DecimalFormat("######0.00");
        //流量占比列表
        List<WriteContrast> flowOfs = new ArrayList<>();
        String Name = "";
        WriteContrast flowOf = new WriteContrast();
        for (JinPin jinPin : list) {
            String goodsInfo = jinPin.getGoodsInfo();
            if (!jinPin.getShopSource().equals(Name)) {
                flowOf = new WriteContrast();
                Name = jinPin.getShopSource();
            }
            //流量渠道命名
            flowOf.setShopSource(jinPin.getShopSource());

            if (goodsInfo.contains("本店商品")) {
                if (jinPin.getAccessCount().contains("-")) {
                    flowOf.setMyShop("-");
                } else {
                    //当前商品访问量除于当前汇总
                    Double l = Double.parseDouble(jinPin.getAccessCount()) / mySum;
                    flowOf.setMyShop(df.format(l));
                }
                continue;
            }
            if (goodsInfo.contains("竞品1")) {
                if (jinPin.getAccessCount().contains("-")) {
                    flowOf.setVieOne("-");
                } else {
                    Double l = Double.parseDouble(jinPin.getAccessCount()) / vieOneSum;
                    flowOf.setVieOne(df.format(l));
                }
                continue;
            }
            if (goodsInfo.contains("竞品2")) {
                if (jinPin.getAccessCount().contains("-")) {
                    flowOf.setVieTwo("-");
                } else {
                    Double l = Double.parseDouble(jinPin.getAccessCount()) / vieTwoSum;
                    flowOf.setVieTwo(df.format(l));
                }
                flowOfs.add(flowOf);
            }
        }

        flowOfs = flowOfs.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(
                Comparator.comparing(WriteContrast::getShopSource))), ArrayList::new));
        ExcelWriter excelWriter = null;
        String eFileName = "D:\\流量结构对比统计图.xlsx";

        excelWriter = EasyExcel.write(eFileName, WriteContrast.class).build();

        //写入
        WriteSheet writeSheet = EasyExcel.writerSheet(0, "流量对比").build();
        excelWriter.write(writeContrasts, writeSheet);

        //写入
        writeSheet = EasyExcel.writerSheet(1, "转化").build();
        excelWriter.write(conversionRates, writeSheet);

        //写入
        writeSheet = EasyExcel.writerSheet(2, "占比").build();
        excelWriter.write(flowOfs, writeSheet);

        //刷新关流
        excelWriter.finish();
        return ReturnBody.success();
    }


    public ExcelWriter testWrite(List<WriteContrast> list, int index, String shellName) {
        return null;
    }

    @ApiOperation("sendText")
    @PostMapping("sendText")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "id", required = false),
    })
    public String sendText(String openId, String content) {
        JSONObject object = new JSONObject(true);
        object.put("remark", "测试的备注");
        object.put("content", content);
        WxTemplateMsgUtils.miniSendRegister(openId, object);
        return ReturnBody.success();
    }

}
